#!/usr/bin/python
# author dennis
# 2022年06月16日
import select
import socket
import sys


def tcp_client():
    client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    dest_addr = ('192.168.131.128', 2000)
    client.connect(dest_addr)
    id_name = input("请输入ID:")
    epoll = select.epoll()  # 创建一个epoll对象
    # 让epoll监控new_client sys.stdin
    epoll.register(client.fileno(), select.EPOLLIN)
    epoll.register(sys.stdin.fileno(), select.EPOLLIN)
    while True:
        # 谁的缓冲区有数据，就填写到events
        events = epoll.poll(-1)
        for fd, event in events:
            if fd == client.fileno():
                data = client.recv(100)
                if data:
                    print(data.decode('utf8'))
                else:
                    break
            elif fd == sys.stdin.fileno():
                try:
                    data = input()  # 服务器端说话，发给对方
                    client.send((id_name + ':' + data).encode('utf8'))
                except EOFError:
                    return

    client.close()


if __name__ == '__main__':
    tcp_client()
